<template>
    <div>
        <h3>发表评论</h3>
        <hr>
        <textarea placeholder="请输入要bb的内容（最多吐槽120字）" maxlength="120" v-model="msg"></textarea>
        <mt-button type="primary" size="large" @click="postMsg">发表评论</mt-button>

        <div class="cmt-list">
            <div class="cmt-item" v-for="(item,i) in comment" :key="i">
                <p class="cmt-item-title">第{{i+1}}楼&nbsp;用户:{{ item.user_name }}&nbsp;发表时间:{{ item.add_time | dateFormat }}</p>
                <p class="cmt-item-body">{{ item.content }}</p>
            </div>
        </div>


        <mt-button type="danger" size="large" plain @click="loadMore">加载更多</mt-button>
    </div>
</template>

<script>
//按需从MintUI导入需要的弹框组件
import {Toast} from 'mint-ui'

export default {
    data() {
        return {
            page:1,//默认放第一页的评论
            comment:[],
            msg:''
        }
    },
    methods:{
        async getComment(){
            //获取评论数据
            const {data}=await this.$http.get('/api/getcomments/'+this.id+'?pageindex='+this.page)
            if(data.status===0) return(this.comment=this.comment.concat(data.message))
        },
        loadMore(){
            //加载更多评论
            this.page++
            this.getComment()
        },
        async postMsg(){
            //发表评论
            //校验，不能为空和输入空格
            if(this.msg.trim().length<=0) return Toast("请填写评论内容~")
            const {data} = await this.$http.post('/api/postcomment/'+this.id,{content:this.msg.trim()})
            Toast('发表成功！')
            if(data.status===0) {
                this.comment.unshift({
                    user_name: "匿名用户",
                    add_time: new Date(),
                    content: this.msg.trim()
                });
            }
            this.msg=""
        }
    },
    props:['id'],//接受父组件传的id
    created(){
        this.getComment()
    }

}
</script>

<style lang="scss" scoped>
    textarea{
        font-size: 13px;
        margin-bottom: 10px;
    }
    .cmt-list{
        margin:20px 0;
        .cmt-item{
            line-height: 20px;
            p{
                color: black;
            }
        }
        .cmt-item-title{
            font-size: 14px;
            background-color: #ddd;
            
        }
        .cmt-item-body{
            font-size: 13px;
            text-indent: 2em;
        }
    }
</style>